using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Terra.Core.Common.ApiResponse;
using Terra.Core.Common.Models.Common;
using Terra.Core.Common.Models.Pagination;
using Terra.Data.Models.Identity;
using Terra.Service.Identity.Interfaces;

namespace Terra.WebApi.Areas.Admin.Controllers;

/// <summary>
/// 部门管理控制器
/// </summary>
/// <remarks>
/// 提供以下功能：
/// <list type="bullet">
/// <item><description>部门查询</description></item>
/// <item><description>部门详情</description></item>
/// <item><description>部门树形结构</description></item>
/// <item><description>部门下拉选择列表</description></item>
/// <item><description>部门创建</description></item>
/// <item><description>部门更新</description></item>
/// <item><description>部门删除</description></item>
/// <item><description>批量删除部门</description></item>
/// <item><description>更新部门状态</description></item>
/// </list>
/// </remarks>
[Area("Admin")]
[ApiController]
[Route("api/admin/depts")]
[ApiExplorerSettings(GroupName = "v1-admin")]
[Authorize]
public class DeptController : ControllerBase
{
    private readonly IDeptService _deptService;
    private readonly ILogger<DeptController> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="deptService">部门服务</param>
    /// <param name="logger">日志记录器</param>
    public DeptController(
        IDeptService deptService,
        ILogger<DeptController> logger)
    {
        _deptService = deptService ?? throw new ArgumentNullException(nameof(deptService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    #region 查询接口

    /// <summary>
    /// 分页获取部门列表
    /// </summary>
    /// <param name="query">查询条件</param>
    /// <returns>部门分页列表</returns>
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse<PagedList<DeptItemDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetPagedDepts([FromQuery] DeptQueryDto query)
    {
        var response = await _deptService.GetPagedDeptsAsync(query);
        return Ok(response);
    }

    /// <summary>
    /// 获取部门详细信息
    /// </summary>
    /// <param name="id">部门ID</param>
    /// <returns>部门详细信息</returns>
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(ApiResponse<DeptDetailDto>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 404)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetDeptById(Guid id)
    {
        var response = await _deptService.GetDeptByIdAsync(id);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 获取部门树形结构
    /// </summary>
    /// <param name="status">状态过滤，默认启用状态</param>
    /// <returns>部门树形结构</returns>
    [HttpGet("tree")]
    [ProducesResponseType(typeof(ApiResponse<List<DeptTreeDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetDeptTree([FromQuery] int? status = 1)
    {
        var response = await _deptService.GetDeptTreeAsync(status);
        return Ok(response);
    }

    /// <summary>
    /// 获取部门选择列表
    /// </summary>
    /// <param name="status">状态过滤，默认启用状态</param>
    /// <returns>部门选择列表</returns>
    [HttpGet("select")]
    [ProducesResponseType(typeof(ApiResponse<List<DeptSelectDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetDeptSelects([FromQuery] int? status = 1)
    {
        var response = await _deptService.GetDeptSelectsAsync(status);
        return Ok(response);
    }

    #endregion

    #region 操作接口

    /// <summary>
    /// 创建部门
    /// </summary>
    /// <param name="dto">创建部门信息</param>
    /// <returns>创建结果</returns>
    [HttpPost]
    [ProducesResponseType(typeof(ApiResponse<Guid>), 201)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> CreateDept([FromBody] DeptCreateDto dto)
    {
        var response = await _deptService.CreateDeptAsync(dto);

        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        return Created($"/api/admin/depts/{response.Data}", response);
    }

    /// <summary>
    /// 更新部门
    /// </summary>
    /// <param name="id">部门ID</param>
    /// <param name="dto">更新部门信息</param>
    /// <returns>更新结果</returns>
    [HttpPut("{id}")]
    [ProducesResponseType(typeof(ApiResponse), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> UpdateDept(Guid id, [FromBody] DeptUpdateDto dto)
    {
        var response = await _deptService.UpdateDeptAsync(id, dto);

        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        return Ok(response);
    }

    /// <summary>
    /// 删除部门
    /// </summary>
    /// <param name="id">部门ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{id}")]
    [ProducesResponseType(typeof(ApiResponse), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> DeleteDept(Guid id)
    {
        var response = await _deptService.DeleteDeptAsync(id);

        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        return Ok(response);
    }

    /// <summary>
    /// 批量删除部门
    /// </summary>
    /// <param name="dto">批量删除参数</param>
    /// <returns>批量删除结果</returns>
    [HttpPost("batch-delete")]
    [ProducesResponseType(typeof(ApiResponse<BatchOperationResult>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> BatchDeleteDepts([FromBody] BatchDeleteDto<Guid> dto)
    {
        if (dto == null || dto.Ids == null || dto.Ids.Count == 0)
        {
            return BadRequest(ApiResponse.Error("VAL001", "请选择需要删除的部门"));
        }

        var response = await _deptService.BatchDeleteDeptsAsync(dto.Ids);

        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        // 即使部分失败也返回200，结果中包含详细信息
        return Ok(response);
    }

    /// <summary>
    /// 更新部门状态
    /// </summary>
    /// <param name="id">部门ID</param>
    /// <param name="status">状态值：1-启用，0-禁用</param>
    /// <returns>更新结果</returns>
    [HttpPut("{id}/status/{status}")]
    [ProducesResponseType(typeof(ApiResponse), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> UpdateDeptStatus(Guid id, int status)
    {
        if (status != 0 && status != 1)
        {
            return BadRequest(ApiResponse.Error("VAL002", "状态值无效，只能为0或1"));
        }

        var response = await _deptService.UpdateDeptStatusAsync(id, status);

        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        return Ok(response);
    }

    #endregion
}